Bee.data.DWRReader = function(recordType, meta){
    Bee.data.DWRReader.superclass.constructor.call(this, meta ? meta : {}, recordType);
};

Ext.extend(Bee.data.DWRReader, Ext.data.DataReader, {
    getJsonAccessor: function(){
        var re = /[\[\.]/;
        return function(expr){
            try {
                return (re.test(expr)) ? new Function("obj", "return obj." + expr) : function(obj){
                    return obj[expr];
                };
            } 
            catch (e) {
            }
            return Ext.emptyFn;
        };
    }(),
    read: function(o){
        var recordType = this.recordType, fields = recordType.prototype.fields;
        if (!this.ef) {
            if (this.meta.id) {
                var g = this.getJsonAccessor(this.meta.id);
                this.getId = function(rec){
                    var r = g(rec);
                    return (r === undefined || r === "") ? null : r;
                };
            }
            else {
                this.getId = function(){
                    return null;
                };
            }
            this.ef = [];
            for (var i = 0; i < fields.length; i++) {
                var f = fields.items[i];
                var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
                this.ef[i] = this.getJsonAccessor(map);
            }
        }
        var root = (o instanceof Array) ? o : [o];
        if (this.meta.defaultItems) {
            root = this.meta.defaultItems.concat(root);
        }
        var records = [], totalRecords = root.length, success = true;
        for (var j = 0; j < totalRecords; j++) {
            var n = root[j];
            var values = {};
            var id = this.getId(n);
            for (var k = 0; k < fields.length; k++) {
                f = fields.items[k];
                var v = this.ef[k](n);
                values[f.name] = f.convert((v !== undefined && v !== null) ? v : f.defaultValue);
            }
            records[j] = new recordType(values, id);
        }
        return {
            success: success,
            records: records,
            totalRecords: totalRecords
        };
    }
});
